package cn.slt.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Collections;
import java.util.Comparator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.slt.domian.Category;
import cn.slt.domian.MD_ClassDSID;
import cn.slt.domian.MD_Metadata;
import cn.slt.domian.MD_ObjDSID;
import cn.slt.domian.MD_libraryDSID;
import cn.slt.service.CategoryService;
import cn.slt.service.MD_MetadataService;
import cn.slt.service.MD_ObjDSIDService;
import cn.slt.service.MD_classDSIDService;
import cn.slt.service.MD_libraryDSIDService;
import cn.slt.service.MD_objContService;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

@Controller

public class CategoryController {
	@Autowired
	private CategoryService service;
	@Autowired
	private MD_MetadataService md_MetadataService;
	@Autowired
	private MD_libraryDSIDService MD_libraryDSIDService;
	@Autowired
	private MD_classDSIDService MD_classDSIDService;
	@Autowired
	private MD_ObjDSIDService MD_ObjDSIDService;

	@RequestMapping("/getMenu")
	public void getMenu(String firCode, String secCode, HttpServletResponse response) {

		JSONArray jsonarray = new JSONArray();
		List<Category> categoryList = service.queryCategoryList(firCode, secCode);
		if (categoryList != null) {
			for (Category category : categoryList) {// for循环简写
				JSONObject json = new JSONObject();
				json.put("thiCode", category.getThiCode());
				json.put("thiName", category.getThiName());
				jsonarray.add(json);
				// jsonarray.put(json);
			}
			response.setCharacterEncoding("utf8");
			try {
				response.getWriter().write(jsonarray.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@RequestMapping("ztreeinit")
	public void ztreeinit(HttpServletResponse response) {
		System.out.println("ztree init");
		JSONArray jsonArray = new JSONArray();
		List<Category> categoryList = service.queryZtree();
		if (categoryList != null) {
			for (Category category : categoryList) {// for循环简写
				JSONObject json1 = new JSONObject();
				json1.put("id", category.getFirCode());
				json1.put("pId", "0");
				json1.put("name", category.getFirName().trim());
				if (!jsonArray.contains(json1)) {
					jsonArray.add(json1);
				}

				JSONObject json2 = new JSONObject();
				json2.put("id", category.getFirCode() + category.getSecCode());
				json2.put("pId", category.getFirCode());
				json2.put("name", category.getSecName().trim());
				if (!jsonArray.contains(json2)) {
					jsonArray.add(json2);
				}

				JSONObject json3 = new JSONObject();
				json3.put("id", category.getFirCode() + category.getSecCode() + category.getThiCode());
				json3.put("pId", category.getFirCode() + category.getSecCode());
				json3.put("name", category.getThiName().trim());
				if (!jsonArray.contains(json3)) {

					jsonArray.add(json3);
				}
			}

			response.setCharacterEncoding("utf8");
			try {
				System.out.println(jsonArray.toString());
				response.getWriter().write(jsonArray.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	@RequestMapping("ztreeaddNodes")
	public void ztreeaddNodes(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		String first = id.substring(0, 2);
		String second = id.substring(2, 4);
		String third = id.substring(4);
		System.out.println(first + second + third);
		JSONArray jsonArray = new JSONArray();
		MD_Metadata metadata = new MD_Metadata();
		metadata.setFirstlev(first);
		metadata.setSecondlev(second);
		metadata.setThirdlev(third);
		List<MD_Metadata> metadatas = md_MetadataService.getby3code(metadata);
		System.out.println(metadatas.toString());

		for (MD_Metadata metadata2 : metadatas) {// for循环简写
			JSONObject json1 = new JSONObject();
			json1.put("id", metadata2.getOwner() + '|' + metadata2.getLocation());
			json1.put("pId", "0");
			json1.put("name", metadata2.getMdName().trim());
			if (!jsonArray.contains(json1)) {
				jsonArray.add(json1);
			}
			Map<String, String> map = new HashMap<String, String>();
			map.put("location", metadata2.getLocation());
			map.put("dsName", metadata2.getOwner().trim());
			int dscode = MD_libraryDSIDService.getdscode(map);
			List<MD_ClassDSID> mDsids = MD_classDSIDService.getBySupdscode(dscode);
			for (MD_ClassDSID dsid : mDsids) {

				JSONObject json2 = new JSONObject();
				json2.put("id", dsid.getDsCode());
				json2.put("pId", metadata2.getOwner() + '|' + metadata2.getLocation());
				json2.put("name", dsid.getDsName() + " " + dsid.getBeizhu());
				if (!jsonArray.contains(json2)) {
					jsonArray.add(json2);
				}
			}
			// JSONObject json3=new JSONObject();
			// json3.put("id",
			// category.getFirCode()+category.getSecCode()+category.getThiCode());
			// json3.put("pId",
			// category.getFirCode()+category.getSecCode());
			// json3.put("name", category.getThiName());
			// jsonArray.add(json3);
		}

		// response.setCharacterEncoding("utf8");
		try {
			// response.getWriter().write(jsonArray.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		metadata.setFirstlev(first);
		metadata.setSecondlev(second);
		metadata.setThirdlev("00");
		metadatas = md_MetadataService.getby3code(metadata);
		System.out.println(metadatas.toString());
		for (MD_Metadata metadata2 : metadatas) {// for循环简写

			Map<String, String> map = new HashMap<String, String>();
			map.put("location", metadata2.getLocation());
			map.put("dsName", metadata2.getOwner());
			int dscode = MD_libraryDSIDService.getdscode(map);
			MD_ClassDSID mDsid = new MD_ClassDSID();
			mDsid.setSupDsCode(dscode);
			mDsid.setLevelcode(third);
			List<MD_ClassDSID> mDsids = MD_classDSIDService.getBySupdscodeandthirdlevel(mDsid);
			if (!mDsids.isEmpty()) {
				System.out.println(mDsids.toString());
				JSONObject json1 = new JSONObject();
				json1.put("id", metadata2.getOwner() + '|' + metadata2.getLocation());
				json1.put("pId", "0");
				json1.put("name", metadata2.getMdName());
				if (!jsonArray.contains(json1)) {
					jsonArray.add(json1);
				}

				for (MD_ClassDSID dsid : mDsids) {

					JSONObject json2 = new JSONObject();
					json2.put("id", dsid.getDsCode());
					json2.put("pId", metadata2.getOwner() + '|' + metadata2.getLocation());
					json2.put("name", dsid.getDsName() + "   " + dsid.getBeizhu());
					if (!jsonArray.contains(json2)) {
						jsonArray.add(json2);
					}
				}
			}
			// JSONObject json3=new JSONObject();
			// json3.put("id",
			// category.getFirCode()+category.getSecCode()+category.getThiCode());
			// json3.put("pId", category.getFirCode()+category.getSecCode());
			// json3.put("name", category.getThiName());
			// jsonArray.add(json3);
		}

		response.setCharacterEncoding("utf8");
		try {
			ArrayList<JSONObject> array = new ArrayList<JSONObject>();   //结果排序并组装返回
			JSONArray jsonArraynew = new JSONArray();
			for (int i = 0; i < jsonArray.size(); i++) {
			    try {
			        array.add(jsonArray.getJSONObject(i));
			    } catch (JSONException e) {
			        // TODO Auto-generated catch block
			        e.printStackTrace();
			    }
			}

			Collections.sort(array, new Comparator<JSONObject>() {

			    @Override
			    public int compare(JSONObject lhs, JSONObject rhs) {
			        // TODO Auto-generated method stub

			        try {
			            return (lhs.getString("name").toLowerCase().compareTo(rhs.getString("name").toLowerCase()));
			        } catch (JSONException e) {
			            // TODO Auto-generated catch block
			            e.printStackTrace();
			            return 0;
			        }
			    }
			});
			for(int i=0;i<array.size();i++)
			jsonArraynew.add(array.get(i));
			response.getWriter().write(jsonArraynew.toString()); //jsonarry2arraylist then sort,at last turn it back to jsonArray and response
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@ResponseBody
	@RequestMapping("showmetadata")
	public String showmetadata(HttpServletRequest request) {
		String[] string = request.getParameter("id").split("\\|");
		String owner = string[0];
		String location = string[1];
		MD_Metadata md_Metadata = md_MetadataService.getone(location, owner);
		Map<String, String> map = new HashMap<String, String>();
		map.put("dsName", owner);
		map.put("location", location);
		MD_libraryDSID md_libraryDSID = MD_libraryDSIDService.gettemp(map);
		Map<String, Object> res = new HashMap<String, Object>();
		res.put("metadata", md_Metadata);
		res.put("libsid", md_libraryDSID);
		return JSONArray.toJSONString(res);
	}

	@ResponseBody
	@RequestMapping("showtablesAndcolunms")
	public String showtablesAndcolunms(HttpServletRequest request) {
		String string = request.getParameter("id");
		Integer dsCode = Integer.parseInt(string);
		MD_ClassDSID mDsid = MD_classDSIDService.getBydscode(dsCode);
		List<MD_ObjDSID> mObjDSIDs = MD_ObjDSIDService.getOjbDsids(dsCode);
		Map<String, Object> res = new HashMap<String, Object>();
		res.put("classdsid", mDsid);
		res.put("objdsid", mObjDSIDs);
		System.out.println(res.toString());
		return JSONArray.toJSONString(res);
	}

	@RequestMapping("firstLevel")
	public void firstLevel(HttpServletResponse response) {
		JSONArray jsonarray = new JSONArray();
		List<Category> list = service.queryFirstLevel();
		if (list != null) {
			for (Category ca : list) {
				JSONObject json = new JSONObject();
				json.put("firCode", ca.getFirCode());
				json.put("firName", ca.getFirName());
				jsonarray.add(json);
			}
		}
		response.setCharacterEncoding("utf8");
		try {
			response.getWriter().write(jsonarray.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping("secondLevel")
	public void secondLevel(HttpServletResponse response, String firCode) {
		JSONArray jsonarray = new JSONArray();
		List<Category> list = service.querySecondLevel(firCode);
		if (list != null) {
			for (Category ca : list) {
				JSONObject json = new JSONObject();
				json.put("secCode", ca.getSecCode());
				json.put("secName", ca.getSecName());
				jsonarray.add(json);
			}
		}
		response.setCharacterEncoding("utf8");
		try {
			response.getWriter().write(jsonarray.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping("thirdLevel")
	public void thirdLevel(HttpServletResponse response, String firCode, String secCode) {
		JSONArray jsonarray = new JSONArray();
		List<Category> list = service.queryCategoryList(firCode, secCode);
		if (list != null) {
			for (Category ca : list) {
				JSONObject json = new JSONObject();
				json.put("thiCode", ca.getThiCode());
				json.put("thiName", ca.getThiName());
				jsonarray.add(json);
			}
		}
		response.setCharacterEncoding("utf8");
		try {
			response.getWriter().write(jsonarray.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping("isExistFirst")
	@ResponseBody
	public String isExistFirst(String firName) {
		boolean mark = service.isExistFirst(firName);
		if (mark)
			return "1";
		else
			return "0";
	}

	@RequestMapping("isExistSecond")
	@ResponseBody
	public String isExistSecond(String firName, String secName) {
		boolean mark = service.isExistSecond(firName, secName);
		if (mark)
			return "1";
		else
			return "0";
	}

	@RequestMapping("isExistThird")
	public void isExistThird(HttpServletResponse response, String firName, String secName, String thiName) {
		try {
			boolean mark = service.isExistThird(firName, secName, thiName);
			if (mark)
				response.getWriter().write("1");// 如果存在
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 批量添加
	 */
	@RequestMapping("addLeveLs_1")
	@ResponseBody
	public String addLeveLs_1(String firName, String secName, String s) {
		List<Object> li = JSONArray.parseArray(s);
		String maxfirCode = service.queryMaxfirCode();
		// System.out.println(maxfirCode);
		int temp;
		if (maxfirCode == null)
			temp = 0;
		else
			temp = Integer.valueOf(maxfirCode);
		int code = temp + 1;
		String firCode;
		if (code < 10)
			firCode = "0" + String.valueOf(code);
		else
			firCode = String.valueOf(code);
		List<Category> list = new ArrayList<Category>();
		for (int i = 0; i < li.size(); i++) {
			JSONObject obj = JSONObject.parseObject(li.get(i).toString());
			Category cate = new Category();
			cate.setFirCode(firCode);
			cate.setFirName(firName);
			cate.setSecCode("01");
			cate.setSecName(secName);
			if (i < 10) {
				cate.setThiCode("0" + String.valueOf(i + 1));
			} else
				cate.setThiCode(String.valueOf(i + 1));
			cate.setThiName(obj.get("value").toString());
			list.add(cate);
		}
		boolean mark = service.addBatch(list);
		if (mark)
			return "1";
		else
			return "0";
	}

	@RequestMapping("addLeveLs_2")
	@ResponseBody
	public String addLeveLs_2(String firCode, String firName, String secName, String s) {
		List<Object> li = JSONArray.parseArray(s);
		String maxSecCode = service.queryMaxSecCode(firCode);
		int temp;
		if (maxSecCode == null)
			temp = 0;
		else
			temp = Integer.valueOf(maxSecCode);
		int code = temp + 1;
		String secCode;
		if (code < 10) {
			secCode = "0" + String.valueOf(code);
		} else
			secCode = String.valueOf(code);
		List<Category> list = new ArrayList<Category>();
		for (int i = 0; i < li.size(); i++) {
			JSONObject obj = JSONObject.parseObject(li.get(i).toString());
			Category cate = new Category();
			cate.setFirCode(firCode);
			cate.setFirName(firName);
			cate.setSecCode(secCode);
			cate.setSecName(secName);
			if (i < 10) {
				cate.setThiCode("0" + String.valueOf(i + 1));
			} else
				cate.setThiCode(String.valueOf(i + 1));
			cate.setThiName(obj.get("value").toString());
			list.add(cate);
		}
		boolean mark = service.addBatch(list);
		if (mark)
			return "1";
		else
			return "0";
	}

	@RequestMapping("addLeveLs_3")
	@ResponseBody
	public String addLeveLs_3(String firCode, String firName, String secCode, String secName, String s) {
		List<Object> li = JSONArray.parseArray(s);
		String maxThiCode = service.queryMaxThiCode(firCode, secCode);
		List<Category> list = new ArrayList<Category>();
		int temp;
		if (maxThiCode == null)
			temp = 0;
		else
			temp = Integer.valueOf(maxThiCode);
		for (int i = 0; i < li.size(); i++) {
			int code = temp + i + 1;
			String thiCode;
			if (code < 10) {
				thiCode = "0" + String.valueOf(code);
			} else
				thiCode = String.valueOf(code);
			JSONObject obj = JSONObject.parseObject(li.get(i).toString());
			Category cate = new Category();
			cate.setFirCode(firCode);
			cate.setFirName(firName);
			cate.setSecCode(secCode);
			cate.setSecName(secName);
			cate.setThiCode(thiCode);
			cate.setThiName(obj.get("value").toString());
			list.add(cate);
		}
		boolean mark = service.addBatch(list);
		if (mark)
			return "1";
		else
			return "0";
	}

	@RequestMapping("delFirst")
	@ResponseBody
	public String delFirst(String firCode) {
		boolean mark = service.delFirst(firCode);
		if (mark) {
			return "1";
		} else
			return "0";
	}

	@RequestMapping("delSecond")
	@ResponseBody
	public String delSecond(String firCode, String secCode) {
		boolean mark = service.delSecond(firCode, secCode);
		if (mark) {
			return "1";
		} else
			return "0";
	}

	@RequestMapping("delThird")
	@ResponseBody
	public String delThird(String firCode, String secCode, String thiCode) {
		boolean mark = service.delThird(firCode, secCode, thiCode);
		if (mark) {
			return "1";
		} else
			return "0";
	}

	/**
	 * 按部门生成的目录树
	 * 
	 * @param response
	 */
	@RequestMapping("searchTreeinit")
	public void searchTreeinit(HttpServletResponse response) {
		System.out.println("Searhtree init");
		JSONArray jsonArray = new JSONArray();
		List<String> categoryList = new ArrayList<String>();
		categoryList.add("办公室");
		categoryList.add("政法处");
		categoryList.add("规计处");
		categoryList.add("水资源处");
		categoryList.add("公管处");
		categoryList.add("基建处");
		categoryList.add("科技处");
		categoryList.add("财审处");
		categoryList.add("农水处");
		categoryList.add("移民办");
		categoryList.add("防办");
		categoryList.add("水政总队");
		categoryList.add("建设局");
		categoryList.add("南水北调");
		categoryList.add("水文局 ");
		categoryList.add("河道局");
		if (categoryList != null) {
			for (String category : categoryList) {// for循环简写
				JSONObject json1 = new JSONObject();
				int id=categoryList.indexOf(category);
				String idString=String.valueOf(id);
				json1.put("id",idString);
				json1.put("pId","00");
				json1.put("name", category.trim());
				if (!jsonArray.contains(json1)) {
					jsonArray.add(json1);
				}

				/*
				 * JSONObject json2 = new JSONObject(); json2.put("id",
				 * category.getFirCode() + category.getSecCode());
				 * json2.put("pId", category.getFirCode()); json2.put("name",
				 * category.getSecName().trim()); if
				 * (!jsonArray.contains(json2)) { jsonArray.add(json2); }
				 * 
				 * JSONObject json3 = new JSONObject(); json3.put("id",
				 * category.getFirCode() + category.getSecCode() +
				 * category.getThiCode()); json3.put("pId",
				 * category.getFirCode() + category.getSecCode());
				 * json3.put("name", category.getThiName().trim()); if
				 * (!jsonArray.contains(json3)) {
				 * 
				 * jsonArray.add(json3); }
				 */
			}

			response.setCharacterEncoding("utf8");
			try {
				System.out.println(jsonArray.toString());
				response.getWriter().write(jsonArray.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	/**
	 * searchtree 给部门添加节点
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("searchTreeaddNodes")
	public void searchTreeaddNodes(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		int index=Integer.parseInt(id);
		List<String> categoryList = new ArrayList<String>();
		categoryList.add("办公室");
		categoryList.add("政法处");
		categoryList.add("规计处");
		categoryList.add("水资源处");
		categoryList.add("公管处");
		categoryList.add("基建处");
		categoryList.add("科技处");
		categoryList.add("财审处");
		categoryList.add("农水处");
		categoryList.add("移民办");
		categoryList.add("防办");
		categoryList.add("水政总队");
		categoryList.add("建设局");
		categoryList.add("南水北调");
		categoryList.add("水文局 ");
		categoryList.add("河道局");
		String name=categoryList.get(index);
		List<MD_Metadata> metadatas = md_MetadataService.getall(name);
		System.out.println(metadatas);
//		List<MD_libraryDSID> list2 = MD_libraryDSIDService.getall(id);
		// for(MD_Metadata l :list)
		// {
		// System.out.println(l.getBuildUnit());
		// System.out.println(l.getOwner());
		// }
		// String first = id.substring(0, 2);
		// String second = id.substring(2, 4);
		// String third = id.substring(4);
		// System.out.println(first + second + third);
		JSONArray jsonArray = new JSONArray();
		// MD_Metadata metadata = new MD_Metadata();
		// metadata.setFirstlev(first);
		// metadata.setSecondlev(second);
		// metadata.setThirdlev(third);
		// List<MD_Metadata> metadatas =
		// md_MetadataService.getby3code(metadata);
		// System.out.println(metadatas.toString());

		for (MD_Metadata metadata2 : metadatas) {// for循环简写
			JSONObject json1 = new JSONObject();
			json1.put("id", metadata2.getOwner() + '|' + metadata2.getLocation());
			json1.put("pId", "0");
			json1.put("name", metadata2.getMdName().trim());
			if (!jsonArray.contains(json1)) {
				jsonArray.add(json1);
			}
			Map<String, String> map = new HashMap<String, String>();
			map.put("location", metadata2.getLocation());
			map.put("dsName", metadata2.getOwner().trim());
			int dscode = MD_libraryDSIDService.getdscode(map);
			List<MD_ClassDSID> mDsids = MD_classDSIDService.getBySupdscode(dscode);
			for (MD_ClassDSID dsid : mDsids) {

				JSONObject json2 = new JSONObject();
				json2.put("id", dsid.getDsCode());
				json2.put("pId", metadata2.getOwner() + '|' + metadata2.getLocation());
				json2.put("name", dsid.getDsName() + " " + dsid.getBeizhu());
				if (!jsonArray.contains(json2)) {
					jsonArray.add(json2);
				}
			}
			// JSONObject json3=new JSONObject();
			// json3.put("id",
			// category.getFirCode()+category.getSecCode()+category.getThiCode());
			// json3.put("pId",
			// category.getFirCode()+category.getSecCode());
			// json3.put("name", category.getThiName());
			// jsonArray.add(json3);
		}

		 response.setCharacterEncoding("utf8");
		try {
			 response.getWriter().write(jsonArray.toString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
